<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// use App\Models\Authorization;
// use App\Transformers\AuthorizationTransformer;

class FavoriteController extends BaseController
{

    /**
     * 检查媒资是否已被收藏
     */
    public function vassetiFavorite(Request $request, $spid, $term_id, $vasseti_id)
    {
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '设备ID不能为空!']);
        }
        if (empty($vasseti_id)) {
            return response()->json(['status' => '404', 'data' => '媒资ID为空!']);
        }
        // 是否被收藏 1 已收藏 0 未收藏
        if (DB::table('favorites')->where(['vasseti_id' => $vasseti_id, 'term_id' => $term_id])->first()) {
            $data['favorite_status'] = 1;
            $data['info']            = '已收藏';
        } else {
            $data['favorite_status'] = 0;
            $data['info']            = '未收藏';
        }
        return response()->json(['status' => '200', 'data' => $data]);
    }

    /*
     * 点播收藏
     */
    public function store(Request $request, $spid, $term_id)
    {
        // 媒资ID
        $vassetiId = $request->input('vasset_id');
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '设备ID不能为空!']);
        }
        // 媒资ID
        if (empty($vassetiId)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空!']);
        }
        $vasseti = DB::table('vassetis')->where(['vasseti_id' => $vassetiId])->first();
        if (!$vasseti) {
            return response()->json(['status' => '404', 'data' => '没有找到该资源!']);
        }
        // 根据机顶盒ID查找相关收藏表信息
        if (DB::table('favorites')->where(['term_id' => $term_id, 'vasseti_id' => $vassetiId])->first()) {
            return response()->json(['status' => '404', 'data' => '该资源已收藏!']);
        }
        $data['term_id']    = $term_id;
        $data['vasseti_id'] = $vassetiId;
        $data['add_time']   = date("Y-m-d H:i:s");
        $results            = DB::table('favorites')->insert($data);
        if (!$results) {
            return response()->json(['status' => '404', 'data' => '收藏失败!']);
        } else {
            return response()->json(['status' => '200', 'data' => '收藏成功!']);
        }
    }

    /**
     * 取消收藏
     */
    public function delete(Request $request, $spid, $term_id)
    {
        // 媒资ID
        $vassetiId = $request->input('vasset_id');
        // 机顶盒ID
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '机顶盒ID不能为空!']);
        }
        // 媒资ID
        if (empty($vassetiId)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空!']);
        }

        if (!DB::table('favorites')->where(['term_id' => $term_id, 'vasseti_id' => $vassetiId])->get()) {
            return response()->json(['status' => '404', 'data' => '无此收藏!']);
        }

        if (DB::table('favorites')->where(['term_id' => $term_id, 'vasseti_id' => $vassetiId])->delete()) {
            return response()->json(['status' => '200', 'data' => '取消收藏成功!']);
        } else {
            return response()->json(['status' => '404', 'data' => '取消收藏失败!']);
        }
    }
    /**
     * 展示全部收藏信息
     */
    public function favoriteList(Request $request, $spid, $term_id)
    {
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '设备ID不能为空!']);
        }

        // 取出所有的媒资ID
        $tagIds = DB::table('favorites')
            ->Join('vasseti_vcattags', 'favorites.vasseti_id', '=', 'vasseti_vcattags.vasseti_id')
            ->where(['favorites.term_id' => $term_id])
            ->select(DB::raw('DISTINCT vasseti_vcattags.vcattag_id'))
            ->get();
        if (empty($tagIds)) {
            return response()->json(['status' => '404', 'data' => '资源为空!']);
        }
        // FTP 配置
        $ftpUrl = config('app.host.ftp');

        $data  = [];
        $datas = [];
        foreach ($tagIds as $key => $value) {
            // 查询分类相关信息
            $vcattag = DB::table('vcattags')->where(['vcattag_id' => $value->vcattag_id])->first();
            if (empty($vcattag)) {
                return response()->json(['status' => '404', 'data' => '没有找到此分类!']);
            }
            $data['vcattag_id']                  = $vcattag->vcattag_id;
            $data['title']                       = $vcattag->title;
            $data['name']                        = $vcattag->name;
            $data['onfocus']['route']['tplType'] = '';
            $data['onfocus']['route']['tplID']   = '';
            $data['onfocus']['href']             = url("/{$spid}/ugc/favorite/{$term_id}/{$value->vcattag_id}/vasset/list1?page=1&limit=12");

            $data['onclick']['route']['tplType'] = '';
            $data['onclick']['route']['tplID']   = '';
            $data['onclick']['href']             = url("/{$spid}/ugc/favorite/{$term_id}/{$value->vcattag_id}/vasset/list1?page=1&limit=12");
            // 获取当前分类下的所有的媒资
            $vassetiIds = DB::table('vasseti_vcattags')->where(['vcattag_id' => $value->vcattag_id])->pluck('vasseti_id')->unique();
            // 统计总数
            $total = DB::table('favorites')->where(['term_id' => $term_id])->whereIn('vasseti_id', $vassetiIds)->count();
            // 第一页
            if ($total > 12) {
                $total = ceil($total / 12);
            } else {
                $total = 1;
            }
            $data['total'] = $total;
            $favorites     = DB::table('favorites')
                ->where(['favorites.term_id' => $term_id])
                ->Join('vassetis', 'favorites.vasseti_id', '=', 'vassetis.vasseti_id')
                ->whereIn('favorites.vasseti_id', $vassetiIds)
                ->select('favorites.add_time', 'vassetis.*')
                ->orderBy('add_time', 'DESC')
                ->limit(12)
                ->get()
                ->unique('vasseti_id');
            if (empty($favorites)) {
                $data['data'] = [];
            } else {
                $vasseti  = [];
                $vassetis = [];
                foreach ($favorites as $favoritesKey => $favoritesValue) {
                    // $vassetis[$favoritesKey] = self::getVasseti($favoritesValue->vasseti_id, $term_id);
                    //媒资ID
                    $vasseti['vasseti_id'] = $favoritesValue->vasseti_id;
                    // 添加收藏时间
                    $vasseti['add_time'] = $favoritesValue->add_time;
                    // 标题
                    $vasseti['title'] = $favoritesValue->title;
                    // 副标题
                    $vasseti['subtitle'] = $favoritesValue->subtitle;
                    // 图片
                    $img = json_decode($favoritesValue->imgs, 1);
                    if (empty($img)) {
                        $vasseti['img'] = (object) [];
                    } else {
                        foreach ($img as $imgKey => $imgValue) {
                            $imgHref = image_match($imgValue['href'], 'SIMG');
                            if ($imgHref) {
                                $vasseti['img'] = $ftpUrl . $imgHref;
                                break;
                            } else {
                                $vasseti['img'] = (object) [];
                            }
                        }
                    }
                    // 当前模板类型,当前模板类型编号
                    $vasseti['onclick']['route']['tplType'] = "DETAIL";
                    $vasseti['onclick']['route']['tplID']   = "";
                    // 直播目前走点播的路由
                    $vasseti['onclick']['href'] = url("/{$spid}/{$term_id}/vasset/{$favoritesValue->vasseti_id}/meta");
                    $vassetis[]                 = $vasseti;
                }
                $data['data'] = $vassetis;
            }

            $datas[] = $data;
        }
        return response()->json(['status' => '200', 'data' => $datas]);
    }

    /**
     * 展示收藏分类列表
     */
    public function favoriteList0(Request $request, $spid, $term_id)
    {
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '设备ID不能为空!']);
        }
        // 唯一标志
        // 查询所有的分类
        $tags = DB::table('favorites as f')
            ->where(['term_id' => $term_id])
            ->Join('vassetis as v', 'f.vasseti_id', '=', 'v.vasseti_id')
            ->Join('vasseti_vcattags as vv', 'f.vasseti_id', '=', 'vv.vasseti_id')
            ->pluck('vv.vcattag_id')
            ->unique();
        if (empty($tags)) {
            return response()->json(['status' => '404', 'data' => '分类为空!']);
        }
        $data  = [];
        $datas = [];
        foreach ($tags as $key => $value) {
            $vcattag = DB::table('vcattags')->where(['vcattag_id' => $value])->first();
            if (!empty($vcattag)) {
                $data['vcattag_id']                  = $vcattag->vcattag_id;
                $data['title']                       = $vcattag->title;
                $data['name']                        = $vcattag->name;
                $data['onfocus']['route']['tplType'] = '';
                $data['onfocus']['route']['tplID']   = '';
                $data['onfocus']['href']             = url("/{$spid}/ugc/favorite/{$term_id}/{$value}/vasset/list1?page=1&limit=12");

                $data['onclick']['route']['tplType'] = '';
                $data['onclick']['route']['tplID']   = '';
                $data['onclick']['href']             = url("/{$spid}/ugc/favorite/{$term_id}/{$value}/vasset/list1?page=1&limit=12");
                $datas[]                             = $data;
            }
        }
        return response()->json(['status' => '200', 'data' => $datas]);
    }

    /**
     * 根据分类获取收藏媒资列表
     */
    public function favoriteList1(Request $request, $spid, $term_id, $vcattag_id)
    {
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '设备ID不能为空!']);
        }
        // 循环拼装以及数据
        $page  = $request->input('page', 1);
        $limit = $request->input('limit', 12);
        $skip  = $page ? ($page - 1) * $limit : 0;
        // 唯一标志
        if (empty($vcattag_id)) {
            return response()->json(['status' => '404', 'data' => '设备ID不能为空!']);
        }
        // 根据分类ID查找相关分类信息
        $vcattag = DB::table('vcattags')->where(['vcattag_id' => $vcattag_id])->first();
        if (empty($vcattag)) {
            return response()->json(['status' => '404', 'data' => '没有找到此分类!']);
        }
        $data = [];
        // 根据分类以及设备ID查找相关媒资信息
        $data['title']                       = $vcattag->title;
        $data['name']                        = $vcattag->name;
        $data['onfocus']['route']['tplType'] = '';
        $data['onfocus']['route']['tplID']   = '';
        $data['onfocus']['href']             = url("/{$spid}/ugc/favorite/{$term_id}/{$vcattag_id}/vasset/list1?page=1&limit=12");

        $data['onclick']['route']['tplType'] = '';
        $data['onclick']['route']['tplID']   = '';
        $data['onclick']['href']             = url("/{$spid}/ugc/favorite/{$term_id}/{$vcattag_id}/vasset/list1?page=1&limit=12");
        // 获取当前分类下的所有的媒资
        $vassetiIds = DB::table('vasseti_vcattags')->where(['vcattag_id' => $vcattag_id])->pluck('vasseti_id')->unique();
        if (empty($vassetiIds)) {
            return response()->json(['status' => '404', 'data' => '分类下媒资为空!']);
        }
        // FTP 配置
        $ftpUrl = config('app.host.ftp');
        $favorites = DB::table('favorites')
            ->Join('vassetis', 'favorites.vasseti_id', '=', 'vassetis.vasseti_id')
            ->where(['term_id' => $term_id])
            ->whereIn('favorites.vasseti_id', $vassetiIds)
            ->orderBy('add_time', 'DESC')
            ->skip($skip)
            ->take($limit)
            ->get()
            ->unique('vasseti_id');
        if (empty($favorites)) {
            $data['data'] = [];
        } else {
            $vasseti  = [];
            $vassetis = [];
            foreach ($favorites as $key => $value) {
                //媒资ID
                $vasseti['vasseti_id'] = $value->vasseti_id;
                // 标题
                $vasseti['title'] = $value->title;
                // 副标题
                $vasseti['subtitle'] = $value->subtitle;
                // 图片
                $img = json_decode($value->imgs, 1);
                if (empty($img)) {
                    $vasseti['img'] = (object) [];
                } else {
                    foreach ($img as $imgKey => $imgValue) {
                        $imgHref = image_match($imgValue['href'], 'SIMG');
                        if ($imgHref) {
                            $vasseti['img'] = json_decode(json_encode(['href' => $ftpUrl . $imgHref]));
                            break;
                        } else {
                            $vasseti['img'] = (object) [];
                        }
                    }
                }
                // 当前模板类型,当前模板类型编号
                $vasseti['onclick']['route']['tplType'] = "DETAIL";
                $vasseti['onclick']['route']['tplID']   = "";
                // 直播目前走点播的路由
                $vasseti['onclick']['href'] = url("/{$spid}/{$term_id}/vasset/{$value->vasseti_id}/meta");
                $vassetis[]                 = $vasseti;
            }
            $data['data'] = $vassetis;
        }
        // 统计总数
        $total = DB::table('favorites')->where(['term_id' => $term_id])->whereIn('vasseti_id', $vassetiIds)->count();
        // 第一页
        if ($total > 12) {
            $total = ceil($total / 12);
        } else {
            $total = 1;
        }
        $data['modelInfo']['page']['nowpage']   = $page;
        $data['modelInfo']['page']['totalpage'] = $total;
        // 当前页大于或者等于时总页是,页数为当前页
        if ($page >= $total) {
            $rightPage = $total;
        } else {
            $rightPage = $page + 1;
        }
        $data['modelInfo']['page']['rightpage'] = url("/{$spid}/ugc/favorite/{$term_id}/{$vcattag_id}/vasset/list1?page={$rightPage}&limit={$limit}");
        // 当前页
        if ($page <= 1) {
            $leftPage = 1;
        } else {
            $leftPage = $page - 1;
        }
        $data['modelInfo']['page']['leftpage'] = url("/{$spid}/ugc/favorite/{$term_id}/{$vcattag_id}/vasset/list1?page={$leftPage}&limit={$limit}");

        return response()->json(['status' => '200', 'data' => $data]);
    }

    /**
     * 查看收藏信息
     */
    public function show($spid, $term_id)
    {
        // 机顶盒ID
        if (empty($term_id)) {
            return response()->json(['status' => '404', 'data' => '机顶盒ID不能为空!']);
        }

        $favorites = DB::table('favorites')->where(['term_id' => $term_id])->get();
        if (empty($favorites)) {
            return response()->json(['status' => '404', 'data' => '收藏为空!']);
        }
        // FTP 配置
        $ftpUrl = config('app.host.ftp');
        $data   = [];
        $datas  = [];
        foreach ($favorites as $key => $value) {
            $data['vasseti_id'] = $value->vasseti_id;
            $data['term_id'] = $value->term_id;
            $vassetis        = DB::table('vassetis')->where(['vasseti_id' => $value->vasseti_id])->first();
            if (empty($vassetis)) {
                return response()->json(['status' => '404', 'data' => '关联资源为空!']);
            }
            $data['tags'] = explode('&', $vassetis->tags);
            // 图片
            $img = json_decode($vassetis->imgs, 1);
            if (empty($img)) {
                $data['img'] = (object) [];
            } else {
                foreach ($img as $imgKey => $imgValue) {
                    $imgHref = image_match($imgValue['href'], 'SIMG');
                    if ($imgHref) {
                        $data['img'] = $ftpUrl . $imgHref;
                        break;
                    } else {
                        $data['img'] = (object) [];
                    }
                }
            }
            $data['title']                       = $vassetis->title;
            $data['subtitle']                    = $vassetis->subtitle;
            $data['onfocus']['route']['tplType'] = '';
            $data['onfocus']['route']['tplID']   = '';
            $data['onfocus']['href']             = url("/{$spid}/vasset/{$value->vasseti_id}/meta");

            $data['onclick']['route']['tplType'] = '';
            $data['onclick']['route']['tplID']   = '';
            $data['onclick']['href']             = url("/{$spid}/vasset/{$value->vasseti_id}/meta");
            // 收藏时间
            $data['add_time'] = $value->add_time;
            $datas[]          = $data;
        }
        return response()->json(['status' => '200', 'data' => $datas]);
    }

    /**
     * 查看媒资信息
     */
    public static function getVasseti(Request $request, $vasseti_id, $term_id)
    {
        $termid = $request->header('device-token');
        $spid   = 1;
        // FTP 配置
        $ftpUrl   = config('app.host.ftp');
        $data     = [];
        $vassetis = DB::table('vassetis')->where(['vasseti_id' => $vasseti_id])->first();
        if (!empty($vassetis)) {
            //媒资ID
            $data['vasseti_id'] = $vassetis->vasseti_id;
            // 标题
            $data['title'] = $vassetis->title;
            // 副标题
            $data['subtitle'] = $vassetis->subtitle;
            // 图片
            $img = json_decode($vassetis->imgs, 1);
            if (empty($img)) {
                $data['img'] = (object) [];
            } else {
                $img[0]['href'] = $ftpUrl . $img[0]['href'];
                $data['img']    = $img[0];
            }
        } else {
            $data['vasseti_id'] = $vasseti_id;
            // 标题
            $data['title'] = '';
            // 副标题
            $data['subtitle'] = '';
            // 图片
            $data['img'] = (object) [];
        }
        // 当前模板类型,当前模板类型编号
        $data['onclick']['route']['tplType'] = "DETAIL";
        $data['onclick']['route']['tplID']   = "";
        // 直播目前走点播的路由
        $data['onclick']['href'] = url("/{$spid}/{$termid}/vasset/{$vasseti_id}/meta");
        return $data;
    }
}
